package com.org.buildcycle2;

import com.org.buildcycle2.model.Dude;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback{

	// string to identify in logs
	private static final String TAG = GamePanel.class.getSimpleName();
	
	// Private declarations
	private GameThread thread;
	private Dude player;
	
	// Sets game panel, creates game loop thread
	public GamePanel(Context context) {
		super(context);
		getHolder().addCallback(this);
	//	player = new Dude(BitmapFactory.decodeResource(getResources(), R.drawable.dude), 50, 50);
		thread = new GameThread(getHolder(), this);
		setFocusable(true);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
		return;
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder){
		thread.setRun(true);
		thread.start();
	}
	
	// clean shutdown (waits for thread to finish)
	@Override
	public void surfaceDestroyed(SurfaceHolder holder){
		boolean retry_bool = true;
		while(retry_bool){
			try{
				thread.join();
				retry_bool = false;
			}catch(InterruptedException exp){ // uses catch to try again if interrupted
				
			}
		}
	}
	
	// when touched...
	@Override
	public boolean onTouchEvent(MotionEvent event){
		int event_x = (int)event.getX();
		int event_y = (int)event.getY();
		int action = event.getAction() & MotionEvent.ACTION_MASK;
		switch(action){
		case MotionEvent.ACTION_DOWN:
			player.handleAction(event_x, event_y);
			if(event.getY() > getHeight() - 50){
				thread.setRun(false);
				((Activity)getContext()).finish();
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if(player.getTouch()){
				player.setX(event_x);
				player.setY(event_y);
			}
			if(event.getAction() == MotionEvent.ACTION_UP){
				if(player.getTouch()){
					player.setTouch(false);
				}
			}
		}
		return true;
		//return super.onTouchEvent(event);
	}
	
	// draws everything to the screen, background color comes first
	@Override
	protected void onDraw(Canvas canvas){
		canvas.drawColor(Color.BLACK);
		player.draw(canvas);
		//canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.dude), 10, 10, null);
	}
}
